var app = getApp(), fetchApi = require("../../../utils/httpPost.js")
const CryptoJS = require("../../../utils/aesUtil.js")

import Dialog from '../../../component/vant/dialog/dialog';
import Toast from '../../../component/vant/toast/toast';
const message = '是否确认取消该订单？'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgurl: app.getImgUrl(),
    //订单状态订单状态 0 - 未支付 1 - 支付中  2 - 已支付（待核销） 3 - 已核销  
    //4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
    states: [2, 3 ,6],
    currentTab: 0,
    orderstate:-1,
    pageSize:5,
    pageIndex: 1,
    scrollTop: 0,
    scrollHeight:0,
    hasData:false,
    orderList:[],
    loading: false,
    netWork: false,
    isLoading: true,
    visible:false,
    itemData:[],
    from_type:0,
    mer_id:0,
    merList:[],
    merNames:[],
    isShowRefund:false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.data.from_type = parseInt(options.from_type)
    that.setData({
      currentTab:0,
      from_type : that.data.from_type
    })
    that.data.orderstate = that.data.states[0]
    // if(options.mer_id){
    //   this.data.mer_id = options.mer_id;
    // }
  },
  changeMer(e){
    console.log('changeMer',e);
    var mer_id = e.detail;
    this.data.mer_id = mer_id;
    this.data.pageIndex = 1;
    this.initOrderOp()
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpMerList: function () {
    var that = this
    fetchApi.httpPost('/mer/myList',{
      keyword:'',
      shop_type: 0,
      pageIndex: 1,
      pageSize: that.data.pageSize,
    }, function (res) {
      console.log("获取我的商家列表", res)
      if(res.data.totalcount > 0){
        var mers = res.data.data.mers;
        for (var index in mers) {
          that.data.merList.splice(that.data.merList.length, 0, mers[index]);
        }
      }
      that.data.mer_id = that.data.merList.length > 0 ?  that.data.merList[0].id : 0;
      that.setData({ 
        merList: that.data.merList,
        merNames:res.data.data.mer_names,
        mer_id:that.data.merList.length > 0 ?  that.data.merList[0].id : 0,
      });
      
      that.onHttpInit(that.data.orderstate)
      // that.setData({ isLoading: false, loading: true, netWork: true })
      // complete
      wx.stopPullDownRefresh() //停止下拉刷新
    },function(){})
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function (state) {
    console.log('onHttpInit',state);
    var that = this;
    fetchApi.httpPost('/product/order/mer/list', {
      state: state,
      mer_id: that.data.mer_id,
      pageSize: that.data.pageSize,
      pageIndex: that.data.pageIndex
    }, function (res) {
      if (res.data.code == 0) {
        if (res.data.totalcount > 0) {
          that.data.pageIndex = that.data.pageIndex + 1
          console.log("订单列表数据", res)
          var orders = res.data.data.orders;
          if(orders.length > 0){
            for (var index in orders) {
              that.data.orderList.splice(that.data.orderList.length, 0, orders[index]);
            }
            that.setData({
              hasData: true,
              orderList: that.data.orderList
            })
          }
        }
      }else{
        Toast.fail(res.data.msg);
      }
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
  },
  handleChange({ detail }) {
    console.log('handleChange',detail.index);
    var that = this
    this.data.pageIndex = 1;
    that.setData({
      // currentTab: detail.index,
      loading: false,
      netWork: false,
      isLoading: true,
      hasData:false,
      orderList:[]
    });
    // 订单状态   0 - 待支付  1 - 支付中  2 - 已支付，待上线   3 - 取消订单
    // 4 - 已上线，检车中  5 - 检车成功  6 - 检车失败  7 - 退款中  8 - 已退款
    that.data.orderstate = that.data.states[detail.index]
    that.onHttpInit(that.data.orderstate)
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var isLogin = app.getStorageSync("isLogin");
    if (!isLogin) {
      wx.navigateTo({
        url: '/pages/login/index',
      })
    } else {
      this.initOp()
    }
  },
  goOrderDetail:function(t){
    console.log('t',t)
    var state = t.currentTarget.dataset.state;
    var orderid = t.currentTarget.dataset.orderid;
    var mer_id = t.currentTarget.dataset.merid;
    wx.navigateTo({
      url: "/pages/order/detail/index?state=" + state + "&order_id=" + orderid + "&mer_id=" + mer_id
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.initOp()
  },
  initOp:function(){
    this.data.pageIndex = 1
    this.setData({
      loading: false,
      netWork: false,
      isLoading: true,
      hasData:false,
      orderList:[]
    })
    this.onHttpMerList();
  },
  initOrderOp:function(){
    this.data.pageIndex = 1
    // this.data.pageSize = 10
    this.setData({
      currentTab: 0,
      loading: false,
      netWork: false,
      isLoading: true,
      hasData:false,
      orderList:[]
    })
    this.onHttpInit(this.data.orderstate)
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      isLoading: true
    })
    this.onHttpInit(this.data.orderstate)
  },
  //同意退款
  accessRefund(e){
    console.log('accessRefund e',e)
    var orderId = e.currentTarget.dataset.orderid;
    var that = this;
    var message = "是否同意该退款？"
    Dialog.confirm({
      title: '订单退款',
      message
    }).then(() => {
      that.onHttpRefundOrderSubmit(orderId)
    })
    .catch(() => {
      Dialog.close();
    });
  },
  onHttpRefundOrderSubmit: function (orderId){
    console.log('orderId',orderId)
    var that = this
    fetchApi.httpPost('/pay/requestRefund', {
      order_id: orderId,
    }, function (res) {
      console.log("订单退款确认同意 返回数据", res)
      if (res.data.code == 0) {
        Toast.success('订单退款确认成功');
        that.initOp()
      } else {
        Toast.fail(res.data.msg);
      }
    },function(){})
  },
  //拒绝退款
  refuseRefund(e){
    var orderId = e.currentTarget.dataset.orderid;
    this.data.refundOrderId = orderId;
    this.setData({
      isShowRefund:true
    })
  },
  onRefundClose(e){
    console.log('onRefundClose',e);
    if(e.detail == "confirm"){//确认
      this.onHttpRefundOrder()
    }
  },
  onHttpRefundOrder: function (){
    var that = this
    fetchApi.httpPost('/pay/requestRefund', {
      order_id: that.data.refundOrderId,
    }, function (res) {
      console.log("拒绝订单退货 返回数据", res)
      if (res.data.code == 0) {
        Toast.success('操作成功');
        that.initOp()
      } else {
        Toast.fail(res.data.msg);
      }
    },function(){})
  },
  // goVerifyOrder(e){
  //   var orderId = e.currentTarget.dataset.orderid;
  //   var that = this;
  //   var message = "是否确认核销？"
  //   Dialog.confirm({
  //     title: '订单核销',
  //     message
  //   }).then(() => {
  //     that.onHttpVerifyOrderSubmit(orderId)
  //   })
  //   .catch(() => {
  //     Dialog.close();
  //   });
  // },
  onHttpVerifyOrderSubmit: function (orderId){
    console.log('orderId',orderId)
    var that = this
    fetchApi.httpPost('/product/order/verifyOrder', {
      order_id: orderId,
    }, function (res) {
      console.log("订单核销确认 返回数据", res)
      if (res.data.code == 0) {
        Toast.success('订单退款确认成功');
        that.initOp()
      } else {
        Toast.fail(res.data.msg);
      }
    },function(){})
  },

  goVerifyOrder: function (res) {
    console.log('scanCode res',res)
    var that = this;
    var isLogin = app.getStorageSync("isLogin");
    var estate_id = app.getStorageSync("estate_id");
    that.data.from_page = 'scancode'
    if (!isLogin) {
      wx.navigateTo({
        url: '/pages/login/index',
      })
    } else {
      wx.scanCode({
        success: (res) => {
          console.log("扫码结果", res);
          var qrcontent = res.result;
          console.log('扫码结果',qrcontent)
          var json_param = {}
          var linkParam = qrcontent;
          var order_info_id = 0;
          var qrtype = '';
          var expire_time = 0;
          if (qrcontent.indexOf('qrtype') < 0) {//加密过的数据
            qrcontent = CryptoJS.Decrypt(res.result)//解密
            console.log('解密：qrcontent',qrcontent)
            json_param = JSON.parse(qrcontent);
            qrtype = json_param["qrtype"];
            linkParam = "qrtype=" + json_param["qrtype"] + "&id=" + json_param["id"];
            if(qrcontent.indexOf('orderInfo') >= 0){
              linkParam +="&order_info_id="+ json_param["id"];
              order_info_id = parseInt(json_param["id"]);
              expire_time = parseInt(json_param["expire_time"]);
            }
          }
          console.log('linkParam',linkParam)
          var is_orderInfo_indexof = qrcontent.indexOf('orderInfo');
          if (is_orderInfo_indexof >= 0) {
            this.orderOp(linkParam,order_info_id,expire_time)
          }else{
            Toast.fail('该二维码不属于该操作');
          }
        },
        fail: (res) => { console.log(res); }
      })
    }
  },
  orderOp:function(linkParam,info_id,expire_time){
    fetchApi.httpPost('/product/order/orderInfo', {
      info_id: info_id,
      reset_qr_code:0,
      expire_time:expire_time
    }, function (res) {
      console.log("订单详情信息", res)
      if (res.data.code == 0) {
        wx.navigateTo({ url: '/pagesMer/pages/validateQr/index?' + linkParam })
      } else {
        Toast.fail(res.data.msg);
      }
    }, function () { })
  },
})